package com.weepal.pavement.mqtt.demo.analysis.dataSender;

import com.weepal.pavement.mqtt.demo.config.dataSource.DataSourceThreadLocal;
import com.weepal.pavement.mqtt.demo.mapper.BasicMapper;
import com.weepal.pavement.mqtt.demo.vo.MqttDevices;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.LinkedList;

/**
 * 采集数据进入数据库
 *
 * @author mawen
 */
@Component
public class SqlSender {
    @Autowired
    private BasicMapper mapper;

    private final static String FLAG = "null";

    private static final String baseSql = "insert into %s (%s) values (%s)";

    public void send(MqttDevices devices, LinkedList<String> v, String field) {
        DataSourceThreadLocal.setDatasources(devices.getSourceName());

        try {
            v = clearDiff(v, field);
            String sqlVal = stringType(v);
            System.out.println("sqlVal: " + sqlVal);
            String sql = String.format(baseSql, devices.getDatabaseFullName(), field, sqlVal);
            mapper.insertExample(sql);
        } catch (Exception e) {
            System.out.println(e.getMessage());
        } finally {
            DataSourceThreadLocal.removeDatasources();
        }
    }

    //清除数据和配置的字段数目不一致的问题
    private LinkedList<String> clearDiff(LinkedList<String> v, String field) {
        int fieldLength = field.split(",").length;
        int vSize = v.size();
        //长度不一致才需要处理
        if (v.size() != fieldLength) {
            //数据过长裁剪尾部的补齐
            if (v.size() > fieldLength) {
                int i = vSize - fieldLength;
                for (int j = 0; j < i; j++) {
                    v.removeLast();
                }
                //数据过短添加null补齐
            } else {
                int i = fieldLength - vSize;
                for (int j = 0; j < i; j++) {
                    v.addLast(FLAG);
                }
            }
        }
        return v;
    }

    public String stringType(LinkedList<String> v) {
        StringBuilder builder = new StringBuilder();
        int size = v.size();
        for (int i = 0; i < size; i++) {
            String val = v.removeFirst();
            //null 不需要 '' 单引号拼接
            if (val.equals(FLAG)) {
                builder.append(val).append(",");
            } else {
                builder.append("'").append(val).append("'").append(",");
            }
        }
        return builder.substring(0, builder.length() - 1);
    }
}
